package com.yanzhengwu.boot.core.common.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述:
 *
 * @author yanzhengwu
 * @create 2022-11-25 1:07
 */
public class MapUtils {

    public static <T> T mapToObj(Map<String, Object> map, T t) {
        Class<?> aClass = t.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        Map<String, Field> fieldMap = new HashMap<>();
        for (Field field : declaredFields) {
            fieldMap.put(field.getName(), field);
        }
        map.forEach((k, v) -> {
            /*if (v instanceof Map){
                mapToObj((Map<String, Object>) v,t);
            }*/
            if (fieldMap.containsKey(k)) {
                Field field = fieldMap.get(k);
                try {
                    field.setAccessible(true);
                    if (v instanceof Boolean) {
                        if ((Boolean) v) {
                            field.set(t, true);
                        } else {
                            field.set(t, false);
                        }
                    } else {
                        field.set(t, v);
                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
        return t;
    }
}
